package database

import (
	"time"

	"gitee.com/mkwchecking/sr-core/log"
	"gitee.com/mkwchecking/sr-core/log/adapter/glog"
	"gitee.com/mkwchecking/sr-core/storage/database/driver"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

func gormConfig(cfg *driver.Config, logger log.Logger) *gorm.Config {

	return &gorm.Config{
		PrepareStmt: true,
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		Logger: glog.New(logger, mergeLogOption(cfg.Log)),
	}
}

func mergeLogOption(merge *driver.Log) *glog.Config {
	d := &driver.Log{
		Level:         log.InfoLevel,
		SlowThreshold: 200 * time.Millisecond,
		Colorful:      true,
		CallSkip:      2,
		TraceKey:      "X-Request-Id",
	}
	if merge != nil {
		if merge.Level != "" {
			d.Level = merge.Level
		}
		if merge.SlowThreshold != 0 {
			d.SlowThreshold = merge.SlowThreshold
		}
		if merge.Colorful {
			d.Colorful = merge.Colorful
		}
		if merge.CallSkip != 0 {
			d.CallSkip = merge.CallSkip
		}
		if merge.TraceKey != "" {
			d.TraceKey = merge.TraceKey
		}
	}

	return &glog.Config{
		Level:         d.Level,
		SlowThreshold: d.SlowThreshold,
		Colorful:      d.Colorful,
		CallSkip:      d.CallSkip,
		TraceKey:      d.TraceKey,
	}
}
